xquery version "1.0" encoding "UTF-8";
(: Authenticate the user with a username and password against realm :)


(: Declare namespaces :)
declare namespace functx	= "http://www.functx.com";
declare namespace xformsdb	= "http://www.tml.tkk.fi/2007/xformsdb";

(: Declare functions :)
(:~
 : Wraps a sequence of atomic values in XML elements 
 :
 : @author  Priscilla Walmsley, Datypic 
 : @version 1.0 
 : @see     http://www.xqueryfunctions.com/xq/functx_wrap-values-in-elements.html 
 : @param   $values the values to wrap in elements 
 : @param   $elementName the name of the elements to construct 
 :) 
declare function functx:wrap-values-in-elements( $values as xs:anyAtomicType*, $elementName as xs:QName ) as element()* {       
	for $value in $values
		return
			element { $elementName } {
				$value
			}
};

(: Declare external variables :)
declare variable $username as xs:string external;
declare variable $password as xs:string external;

(: Retrieve user :)
let $user	:=	for $user in //xformsdb:users/xformsdb:user
					where $user/@username = $username and $user/@password = $password
					return
						$user

(: Retrieve roles :)
let $roles	:=	tokenize( string( $user/@roles ), "," )
(: Normalize space :)
let $roles	:=	for $role in $roles
					return
						normalize-space( $role )
(: Remove empty roles :)
let $roles	:=	for $role in $roles
					where string-length( $role ) > 0 
					return
						$role
(: Wrap values in elements :)
let $roles	:=	functx:wrap-values-in-elements( $roles, xs:QName( 'xformsdb:role' ) )


(: Return the result :)
return
	if ( exists( $user/@username ) ) then
		element xformsdb:user {
			element xformsdb:username {
				string( $user/@username )
			},
			$roles
		}
	else
		element xformsdb:user {
		}